import {
  getDeInfoByPage,
  addDeInfo,
  updateDeInfo,
  delDeInfo,
  exportDeInfo,
} from '@/services/device/deInfo';
import { InfoCircleOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { ModalForm, ProFormDatePicker, ProFormText } from '@ant-design/pro-components';
import ProTable from '@ant-design/pro-table';
import { tableSearchPublicConfig } from '@/utils/filterUtils';
import {
  Button,
  Tabs,
  Modal,
  Table,
  message,
  Row,
  Col,
  Form,
  DatePicker,
  Tooltip,
  Select,
  Upload,
} from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import dayjs from 'dayjs';

const DeInfo: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState(''); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const [isScrapped, setIsScrapped] = useState(false); //报废日期的disable
  const ref = useRef(null);
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      sorter: true,
      valueType: 'index',
      width: 80,
    },
    /* {
      title: '唯一标识',
      dataIndex: 'identification',
     align: 'center',sorter: true, 
      hideInTable: true,
    }, */
    {
      title: '设备名称',
      dataIndex: 'deviceName',

      align: 'center',
      sorter: true,
      width: 120,
      onCell: () => {
        return {
          style: {
            maxWidth: 100,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer',
          },
        };
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '固资编号',
      align: 'center',
      sorter: true,

      width: 120,
      dataIndex: 'deviceId',
    },
    {
      title: '规格型号',
      dataIndex: 'deviceType',

      align: 'center',
      sorter: true,
      search: false,
      width: 120,
    },
    {
      title: '品牌',
      dataIndex: 'manufacturer',
      align: 'center',
      sorter: true,

      search: false,
      width: 120,
    },
    {
      title: '设备状态',
      dataIndex: 'deviceState', //正常、已报废
      align: 'center',
      sorter: true,

      width: 120,
      valueType: 'select',

      fieldProps: {
        options: [
          {
            label: '正常',
            value: '正常',
          },
          {
            label: '已报废',
            value: '已报废',
          },
        ],
      },
    },
    {
      title: '质保截止日期',
      dataIndex: 'warrantyDate',
      align: 'center',
      sorter: false,

      width: 120,
      search: false,
    },
    {
      title: '报废日期',
      dataIndex: 'scrappedDate',
      align: 'center',
      sorter: true,

      width: 120,
      search: false,
    },
    {
      title: '供应商',
      width: 150,

      align: 'center',
      sorter: true,
      dataIndex: 'vendor',
      onCell: () => {
        return {
          style: {
            maxWidth: 100,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer',
          },
        };
      },
      /* render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ), */
    },
    {
      title: '联系人',
      dataIndex: 'contact',

      align: 'center',
      sorter: true,
      width: 120,
      search: false,
    },
    {
      title: '联系方式',
      width: 120,
      align: 'center',
      sorter: true,

      search: false,
      dataIndex: 'telephone',
    },
    {
      title: '安装位置',
      width: 150,
      align: 'center',
      sorter: true,

      search: false,
      dataIndex: 'location',
    },
    {
      title: '设备类别',
      align: 'center',
      sorter: true,

      width: 120,
      dataIndex: 'category', //s/k/n
    },
    {
      title: '采购编号',
      width: 120,

      align: 'center',
      sorter: true,
      dataIndex: 'contractId',
    },
    {
      title: '采购日期',
      align: 'center',
      sorter: true,
      width: 120,

      search: false,
      dataIndex: 'contractDate',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      search: false,

      align: 'center',
      fixed: 'right',
      width: 120,
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(false);
            setFormTitle('编辑');
            actionRef.current?.reload();
            form.setFieldsValue({
              identification: record.identification,
              deviceName: record.deviceName,
              deviceId: record.deviceId,
              deviceType: record.deviceType,
              manufacturer: record.manufacturer,
              deviceState: record.deviceState,
              warrantyDate: dayjs(record.warrantyDate),
              scrappedDate: dayjs(record.scrappedDate),
              vendor: record.vendor,
              contact: record.contact,
              telephone: record.telephone,
              location: record.location,
              category: record.category,
              contractId: record.contractId,
              contractDate: dayjs(record.contractDate),
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a key="downloadKey" href={`/device/DedownloadDeFile?id=${record.id}`} download>
          下载
        </a>,

        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delDeInfo({ id: record.id });
                actionRef.current!.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const handleSubmit = async (values) => {
    setConfirmLoading(true);
    const submit = form.getFieldsValue();
    /* const submit = {
      category: '',
      contact: '',
      contractDate: '',
      contractId: '',
      deviceId: '',
      deviceName: '',
      deviceState: '',
      deviceType: '',
      id: '',
      identification: '',
      location: '',
      manufacturer: '',
      scrappedDate: '',
      telephone: '',
      vendor: '',
    }; */
    console.log('提交', values);
    if (formTitle == '新建') {
      const result = await addDeInfo(values);
      console.log('提交的结果', result);
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updateDeInfo(submit);
    }
    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current!.reload();
  };

  const handleScrapped = async () => {
    const record = form.getFieldsValue();
    if (record.deviceState == '正常') {
      setIsScrapped(true);
      form.setFieldsValue({
        identification: record.identification,
        deviceName: record.deviceName,
        deviceId: record.deviceId,
        deviceType: record.deviceType,
        manufacturer: record.manufacturer,
        deviceState: record.deviceState,
        warrantyDate: null,
        scrappedDate: null,
        vendor: record.vendor,
        contact: record.contact,
        telephone: record.telephone,
        location: record.location,
        category: record.category,
        contractId: record.contractId,
        contractDate: dayjs(record.contractDate),
        id: record.id,
      });
    } else {
      setIsScrapped(false);
    }
  };
  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="备件库存分析"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={tableSearchPublicConfig}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              const filters = filterTran(ref.current.getFieldsValue());
              exportDeInfo({
                current: 1,
                pageSize: 5000,
                filters: filters,
              }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `DeviceInfo.xls`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }}
            type="primary"
          >
            导出
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const sorters = sortTran(sort);
          const filters = filterTran(params);
          const result = await getDeInfoByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });

          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 1500, y: 350 }}
        rowSelection={{}}
      />
      <ModalForm
        layout="horizontal"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        visible={modalVisit}
        title={formTitle}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <ProFormText
          name="identification"
          label="唯一标识"
          initialValue={1112}
          placeholder="请输入名称"
          hidden={true}
        />
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="deviceName"
              label="设备名称"
              rules={[{ required: true, message: '请输入设备名称!' }]}
              disabled={createOrUpdate}
            />
          </Col>
          <Col span={12}>
            <ProFormText name="deviceId" label="固资编号" disabled={createOrUpdate} />
          </Col>
        </Row>

        {/* <Row gutter={[50, 0]}>
          <Col span={12}>
            
          </Col>
          <Col span={12}>
            
          </Col>
        </Row> */}
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <Form.Item
              name="category"
              label="设备类别"
              rules={[{ required: true, message: '请选择设备类别!' }]}
            >
              <Select disabled={createOrUpdate}>
                <Select.Option value="特种设备">特种设备</Select.Option>
                <Select.Option value="关键设备">关键设备</Select.Option>
                <Select.Option value="一般设备">一般设备</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <ProFormText name="deviceType" label="规格型号" disabled={createOrUpdate} />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText name="location" label="安装位置" disabled={createOrUpdate} />
          </Col>
          <Col span={12}>
            <ProFormText name="manufacturer" label="品牌" disabled={createOrUpdate} />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <Form.Item
              name="deviceState"
              label="设备状态"
              rules={[{ required: true, message: '请选择设备状态!' }]}
            >
              <Select disabled={createOrUpdate} onClick={handleScrapped}>
                <Select.Option value="正常">正常</Select.Option>
                <Select.Option value="已报废">已报废</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="质保截止日期" name="warrantyDate">
              {/* <DatePicker disabled={isScrapped} style={{ width: '100%' }} /> */}
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <Form.Item
              label="报废日期"
              name="scrappedDate"
              rules={[{ required: false, message: '请选择报废日期!' }]}
            >
              {/* <DatePicker disabled={isScrapped} style={{ width: '100%' }} /> */}
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <ProFormText name="vendor" label="供应商" disabled={createOrUpdate} />
          </Col>
        </Row>

        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText name="contact" label="联系人" disabled={createOrUpdate} />
          </Col>
          <Col span={12}>
            <ProFormDatePicker
              name="contractDate"
              label="采购日期"
              rules={[{ required: true, message: '请选择采购日期!' }]}
              width={'100%'}
              disabled={createOrUpdate}
            />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText name="contractId" label="采购编号" disabled={createOrUpdate} />
          </Col>
          <Col span={12}>
            <ProFormText name="telephone" label="联系方式" disabled={createOrUpdate} />
          </Col>
          <Col span={12} />
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <Form.Item label="附件上传">
              <Upload
                action="/device/uploaddeFile"
                method="post"
                listType="text"
                // 这里可以添加更多的上传配置，如文件限制等
              >
                <Button icon={<UploadOutlined />}>点击上传</Button>
              </Upload>
            </Form.Item>
          </Col>
        </Row>
      </ModalForm>
    </PageHeaderWrapper>
  );
};
export default DeInfo;
